package com.yc.damai.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.damai.entity.DmOrderitem;
import com.yc.damai.entity.DmOrders;
import com.yc.damai.entity.DmProduct;
import com.yc.damai.mapper.DmOrderitemMapper;
import com.yc.damai.mapper.DmOrdersMapper;
import com.yc.damai.mapper.DmProductMapper;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("product")
public class ProductDao {

    @Resource
    DmProductMapper productMapper;

    @RequestMapping("queryNewAndHot")
    Map<String, Object> queryNewAndHot(){
        //最新商品
        IPage<DmProduct> page = new Page<>(1,10);
        // 排序
        page.orders().add(OrderItem.desc("id"));
        IPage<DmProduct> iPage = productMapper.selectPage(page, null);
        List<DmProduct> news = iPage.getRecords();

        // 最热
        page = new Page<>(1,10);
        LambdaQueryWrapper<DmProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DmProduct::getIsHot,1);
        iPage = productMapper.selectPage(page, lqw);
        List<DmProduct> hots = iPage.getRecords();

        Map<String,Object> ret = new HashMap<>();
        ret.put("news",news);
        ret.put("hots",hots);

        return ret;

    }


    @Resource
    DmOrdersMapper ordersMapper;
    @Resource
    DmOrderitemMapper orderitemMapper;

    // TODO 秒杀订单的方法 , 定义在 other 中, 通过 消息队列 + 调用other方法方式执行
    @Transactional
    @RabbitListener(queuesToDeclare = @Queue("skQueue"))
    public void secondKillOrder(DmOrders order){
        // aid 收货地址
        // 与普通的区别, 少了扣减库存的操作

        Integer pid = order.getItems().get(0).getPid();
        DmProduct dmProduct = productMapper.selectById(pid);

        order.setTotal(dmProduct.getShopPrice());
        order.setAid(order.getAid());
        order.setState(1);
        order.setCreatetime(LocalDateTime.now());
        ordersMapper.insert(order);
        for (DmOrderitem item : order.getItems()) {
            item.setOid(order.getId());
            item.setCount(1);
            item.setTotal(dmProduct.getShopPrice());
            orderitemMapper.insert(item);
        }
        System.out.println("秒杀订单完成");
    }

}
